package message.activemq.queue;

import cn.hutool.core.util.RandomUtil;
import message.activemq.ActiveMQUtil;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

public class QueueConsumerA {

    //配置服务地址和端口
    private static final String url = "tcp://127.0.0.1:61616";
    //这次发送的消息名称
    private static final String topicName = "queue_style";

    //定义当前消费者名称
    private static final String consumerName = "consumer-" + RandomUtil.randomString(5);

    public static void main(String[] args) throws JMSException {
        //检查activemq服务是否开启
        ActiveMQUtil.checkServer();
        System.out.printf("消费者启动了:%s%n", consumerName);
        //创建ConnectionFactory并绑定url
        ConnectionFactory factory = new ActiveMQConnectionFactory(url);
        //创建Connection
        Connection connection = factory.createConnection();
        //启动连接
        connection.start();
        //创建Session
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        //使用session创建队列
        Destination destination = session.createQueue(topicName);
        //创建消息消费者
        MessageConsumer consumer = session.createConsumer(destination);
        //消费者创建监听器
        consumer.setMessageListener(new MessageListener() {
            public void onMessage(Message arg0) {
                TextMessage textMessage = (TextMessage) arg0;
                try {
                    System.out.println(consumerName + "=>接收消息:" + textMessage.getText());
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        });
        //consumer.close();
        //session.close();
        //connection.close();
    }
}